<template>
    <div class="player-container">
        <div class="player-header ml-center" @click="toCourseDetail">
            <span class="header-playing">正在播放：{{periodInfo.periodName}}</span>
            <span class="header-tips">{{periodInfo.courseName}} > {{periodInfo.chapterName}}</span>
        </div>
        <!-- 定义播放器dom -->
        <div id="J_prismPlayer" class="prism-player player-left"/>

        <!-- 播放列表 -->
        <div class="player-right play-list">
            <h3 class="play-list-title">
                {{ `播放列表` }}
            </h3>
            <dl v-if="playList">
                <el-tooltip
                        effect="light"
                        :content="item.periodName"
                        placement="right"
                        v-for="(item,index) in playList"
                        :key="index">
                    <dd @click="changeVideo(item)"
                        class="play-list-item"
                        :class="{active: playNow === item.videoId}">
                        <i class="iconfont">&#58908;</i>
                        P{{ index+1 + '&nbsp;&nbsp;' + item.periodName}}
                    </dd>
                </el-tooltip>
            </dl>
        </div>
    </div>
</template>

<script>
  import { getPlayAuth } from '@/api/vod'
  import { isBuyVideo } from '@/api/order';
  import { getPeriodInfo,getPeriodVideo } from '@/api/course';
  import { mapGetters } from 'vuex';
  import { addStudy } from '@/api/study';


  export default {
    inject: ['reload'],
    data () {
      return{
        playList: [],
        playNow: '',
        studyRecord: {},
        videoInfo: {
          userId: '',
          videoId: ''
        },
        periodInfo:{
          periodId: '',
          periodName: '',
          periodFree: '',
          courseFree: '',
          courseId: '',
          courseName: '',
          chapterName: ''
        },
        playAuth: '',
        videoId: this.$route.query.videoId
      }
    },
    methods:{
      getAuth(){
        this.videoInfo.userId = this.userId
        this.videoInfo.videoId = this.$route.query.videoId

        // 判断是否购买该课程
        isBuyVideo(this.videoInfo).then(result => {
          let { code, data } = result
          if (code === 20000) {
            //已购买
            if (data.item === 1){
              //获取头部信息
              this.getPeriod()

              // 获取播放凭证
              getPlayAuth(this.videoId).then(result => {
                let { code, data } = result
                if (code === 20000) {
                  this.playAuth = data.playAuth
                  this.initPlayer()

                  //获取播放列表
                  this.getPlayList()

                  //免费课程记录学习进度，收费课程试看课程不记录
                  //免费课程
                  if (this.periodInfo.courseFree === true){
                    this.setStudyRecord()
                  }
                  //收费课程
                  else {
                    if (this.periodInfo.periodFree !== true){
                      this.setStudyRecord()
                    }
                  }
                }
              })
            }
            //没有购买
            else {
              this.$message({
                type: 'error',
                message: '请先购买该课程！'
              });
              getPeriodInfo(this.$route.query.videoId).then(result => {
                const {code,data} = result
                if (code === 20000){
                  this.$router.push("/course/" + data.item.courseId)
                  return;
                }
              })
            }
          }
          //不存在该视频
          else {
            this.$router.push('/404')
          }
        })
      },

      initPlayer(){

        const saveTime = function (memoryPlay) {
          //console.log(memoryPlay.getCurrentTime())
        }

        let player = new Aliplayer({
          id: 'J_prismPlayer',
          width: '60%',
          height: '500px',
          autoplay: false,
          preload: true,
          controlBarVisibility: "hover",
          skinLayout: [
            {
              "name": "bigPlayButton",
              "align": "blabs",
              "x": 30,
              "y": 80
            },
            {
              "name": "H5Loading",
              "align": "cc"
            },
            {
              "name": "errorDisplay",
              "align": "tlabs",
              "x": 0,
              "y": 0
            },
            {
              "name": "infoDisplay"
            },
            {
              "name": "tooltip",
              "align": "blabs",
              "x": 0,
              "y": 56
            },
            {
              "name": "thumbnail"
            },
            {
              "name": "controlBar",
              "align": "blabs",
              "x": 0,
              "y": 0,
              "children": [
                {
                  "name": "progress",
                  "align": "blabs",
                  "x": 0,
                  "y": 44
                },
                {
                  "name": "playButton",
                  "align": "tl",
                  "x": 15,
                  "y": 12
                },
                {
                  "name": "timeDisplay",
                  "align": "tl",
                  "x": 10,
                  "y": 7
                },
                {
                  "name": "fullScreenButton",
                  "align": "tr",
                  "x": 10,
                  "y": 12
                },
                {
                  "name": "setting",
                  "align": "tr",
                  "x": 15,
                  "y": 12
                },
                {
                  "name": "volume",
                  "align": "tr",
                  "x": 5,
                  "y": 10
                },
                {
                  "name": "snapshot",
                  "align": "tr",
                  "x": 5,
                  "y": 10
                }
              ]
            }
          ],
          cover: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=608658939,1456100491&fm=26&gp=0.jpg',
          //播放加密视频
          encryptType: 1,
          //默认标清
          defaultDefinition:'LD',
          vid: this.$route.query.videoId,
          playauth: this.playAuth,
          useH5Prism: true,
          //自定义组件
          components: [{
            name: 'MemoryPlayComponent',
            type: AliPlayerComponent.MemoryPlayComponent,
            args:[false,1,saveTime]
          }]
        })

        /* h5截图按钮, 截图成功回调 */
        player.on('snapshoted', function (data) {
          let pictureData = data.paramData.base64
          let downloadElement = document.createElement('a')
          downloadElement.setAttribute('href', pictureData)
          let fileName = 'Aliplayer' + Date.now() + '.png'
          downloadElement.setAttribute('download', fileName)
          downloadElement.click()
          pictureData = null
        })
      },

      getPeriod(){
        getPeriodInfo(this.$route.query.videoId).then(result => {
          const {code,data} = result
          if (code === 20000){
            this.periodInfo = data.item
          }
        })
      },

      getPlayList(){
        getPeriodVideo(this.$route.query.videoId).then(result => {
          const {code,data} = result
          if (code === 20000){
            this.playList = data.items
            this.playNow = this.$route.query.videoId
          }
        })
      },

      //切换视频
      changeVideo(item){
        if (item.videoId === this.$route.query.videoId){
          return;
        }

        this.$router.push('/player?videoId='+item.videoId)
        //刷新页面
        window.location.reload()
      },

      //跳转至课程详情页
      toCourseDetail(){
        let url = this.$router.resolve({path: '/course/' + this.periodInfo.courseId});
        window.open(url.href, '_blank')
      },

      //记录学习进度
      setStudyRecord(){
        this.studyRecord.userId = this.userId
        this.studyRecord.periodId = this.periodInfo.periodId
        addStudy((this.$qs.stringify(this.studyRecord))).then(result => {})
      }

    },
    created () {
      this.$nextTick(() => {
        this.getAuth()

        //禁用console.log,aliplayer自带bug
        if(!global.consoleSwitch){
          console.log = ()=>{}
        }
      })
    },
    computed: {
      ...mapGetters({
        'userId': 'id'
      }),
    },
  }
</script>

<style scoped lang="stylus">
    @import '~assets/stylus/variables.styl';
    @import '~assets/stylus/mixin.styl';
    .player-header{
        margin-top: 20px;
        height: 60px;
        padding-right: 0.8%;
        cursor: pointer;
    }
    .header-playing{
        line-height: 24px;
        font-size: 20px;
        display: block;
        color: #37f;
    }
    .header-tips{
        margin-top: 10px;
        line-height: 20px;
        font-size: 16px;
        display: block;
    }
    .player-left{
        margin-left: 10%;
        float: left;
    }
    .player-right{
        overflow-y:auto
        width: 24%;
        height: 500px;
        float: left;
        margin-left: 1.5%;
    }
    .play-list{
        background-color: #f4f4f4;
    }
    .play-list-title{
        padding-top: 10px;
        padding-left 15px;
        margin-bottom: 12px;
        font-size: 18px;
        font-weight: 700;
        line-height: 24px;
    }
    .play-list-item{
        display: inline-block;
        margin-right: 12px;
        padding: 15px;
        font-size: 14px;
        color: #9199a1;
        line-height: 16px;
        cursor: pointer;
        width: 85%
        overflow:hidden;
        white-space: nowrap;
        text-overflow:ellipsis;
    }
    .play-list-item:hover{
        color: #37f;
    }
    .active{
        background-color: #eaf1ff;
        border-radius: 8px;
        color: #37f;
        font-weight: 700;
    }


</style>
